package com.updesignsz.admin.controller;

import com.updesignsz.admin.util.QiniuUtil;
import com.updesignsz.admin.util.ResponseUtil;
import com.updesignsz.admin.util.image.ImageBase64Util;
import com.updesignsz.commom.util.ResultVo;
import com.updesignsz.commom.util.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * 上传图片
 * Creation date 2020-8-8 17:53:48
 */
@RestController
public class UploadImageController {

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    /**
     * 项目上传图片
     *
     * @param multipartFile
     * @param response
     */
    @PostMapping(value = "/projectsImage")
    public void projectsImage(@RequestParam(value = "upfile", required = true) MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) {
        ResultVo vo = new ResultVo();
        try {
//            String imgFileName = ImageBase64Util.saveAsImage(multipartFile.getBytes(), uploadFolder);
            if (!multipartFile.isEmpty()) {
                InputStream inputStream =  multipartFile.getInputStream();
                String path = QiniuUtil.uploadQNImg(inputStream, ResponseUtil.shortUUID() + ".jpg");
                Map<String, Object> map = new HashMap<>();
                map.put("url", path);
                map.put("name", multipartFile.getOriginalFilename());
                vo.setData(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            vo.setResultVo(1, "项目上传图片，格式不正确或值不正确");
        }
        ResponseUtil.outJson(vo.toJsonMsg(), response);
    }

    /**
     * 项目上传图片
     *
     * @param multipartFile
     * @param response
     */
    @PostMapping(value = "/uploadImage")
    public void uploadImage(@RequestParam(value = "upfile", required = true) MultipartFile multipartFile, HttpServletResponse response) {
        JSONObject map = new JSONObject();
        try {
            if (!multipartFile.isEmpty()) {
                InputStream inputStream =  multipartFile.getInputStream();
                String path = QiniuUtil.uploadQNImg(inputStream, ResponseUtil.shortUUID() + ".jpg");
                String[] array = new String[1];
                array[0] = path;
                map.put("errno", 0);
                map.put("data", array);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("errno", 1);
        }
        ResponseUtil.outJson(map.toString(), response);
    }
}
